package com.app.system.utils;

import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zt on 2021-07-13
 */
public class GetDifference {
    public static Map<String, String> getDifference(Object a, Object b)
            throws IllegalArgumentException, IllegalAccessException {
        Map<String, String> map = new HashMap<String, String>();
            Field[] declaredFields2 = a.getClass().getDeclaredFields();
            Field[] declaredFields23 = b.getClass().getDeclaredFields();

            StringBuilder xiugaiqian = new StringBuilder();
            StringBuffer xiugaihou = new StringBuffer();
            for (int i = 0; i < declaredFields2.length; i++) {
                declaredFields2[i].setAccessible(true);
                declaredFields23[i].setAccessible(true);
                if (declaredFields2[i].get(a) != null && declaredFields23[i].get(b) != null) {

                    if (!declaredFields2[i].get(a).equals(declaredFields23[i].get(b))) {
                        xiugaiqian.append(declaredFields2[i].getName() + ":" + declaredFields2[i].get(a)).append(",");
                        xiugaihou.append(declaredFields23[i].getName() + ":" + declaredFields23[i].get(b)).append(",");
                    }
                } else if (declaredFields2[i].get(a) == null && declaredFields23[i].get(b) != null) {
                    xiugaiqian.append(declaredFields2[i].getName() + ":" + null).append(",");
                    xiugaihou.append(declaredFields23[i].getName() + ":" + declaredFields23[i].get(b)).append(",");
                } else if (declaredFields2[i].get(a) != null && declaredFields23[i].get(b) == null) {
                    xiugaiqian.append(declaredFields2[i].getName() + ":" + declaredFields2[i].get(a)).append(",");
                    xiugaihou.append(declaredFields23[i].getName() + ":" + null).append(",");
                }
            }

            if (StringUtils.isNoneBlank(xiugaiqian.toString()) && StringUtils.isNoneBlank(xiugaihou.toString())) {
                map.put(xiugaiqian.toString().substring(0, xiugaiqian.length() - 1),
                        xiugaihou.toString().substring(0, xiugaihou.length() - 1));
            }

        return map;

    }

}
